package api

import (
	"TaskAssignmentSystem/internal/admin/dao"
	"TaskAssignmentSystem/internal/admin/services"
	"TaskAssignmentSystem/internal/pkg/middleware/handler"
	"TaskAssignmentSystem/pkg/utils"
	"errors"
	"fmt"
	"github.com/kataras/iris/v12"
	"gorm.io/gorm"
)

const (
	MsgReadStatusNo  = 0 //消息状态-未读
	MsgReadStatusYes = 1 //消息状态-已读

	TypeMsg = 0 //消息类型-消息通知
	/*TypeIncome   = 1 //消息类型-收入记录
	TypeExchange = 2*/ //消息类型-兑换记录

	BalanceLogLogTypeIn  = 1
	BalanceLogLogTypeOut = 2
)

/*
 *  SendMessageToProjectRequest
 *  @Description: 发送消息推送到项目权限下的请求参数，持有当前这个项目权限的用户都会收到相关消息
 */

type SendMessageToProjectRequest struct {
	ProjectId string `json:"project_id"`
	Content   string `json:"content"`
}

// @Summary 发送通知
// @Description 向项目发送通知
// @Tags 通知
// @Accept application/json
// @Produce application/json
// @param Accept-Version header string true "1.0.0"
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param param body SendMessageToProjectRequest true "发送通知参数"
// @Success 200 {object} utils.Response --> 成功后返回数据结构
// @Failure 400 {object} utils.ResponseError --> 失败后返回数据结构
// @Router /admin/message/send [post]
func SendMessageToProjectHandler(ctx iris.Context) {
	var RequestParams SendMessageToProjectRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	//var common dao.Common[dao.SystemMsg]
	var messageServe services.MessageService

	if err := messageServe.SendMessage(RequestParams.ProjectId, RequestParams.Content); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	} else {
		ctx.JSON(utils.Response{Code: iris.StatusOK, Message: iris.StatusText(iris.StatusOK), Data: iris.StatusText(iris.StatusOK)})
		return
	}

}

/*
 *  MessageListRequest
 *  @Description: 后台管理系统中，获取消息列表的请求参数，Page 分页页码、PageSize 分页每页需要返回的条数
 */

type MessageListRequest struct {
	Page              int64 `json:"page"`
	PageSize          int64 `json:"page_size"`
	MsgClassification int   `json:"msg_classification" validate:"required"`
}

// @Summary 通知消息列表
// @Description 通知消息列表
// @Tags 通知
// @Accept application/json
// @Produce application/json
// @param Accept-Version header string true "1.0.0"
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param param body MessageListRequest true "通知消息列表参数"
// @Success 200 {object} utils.Response --> 成功后返回数据结构
// @Failure 400 {object} utils.ResponseError --> 失败后返回数据结构
// @Router /admin/message/list [post]
func MessageListHandler(ctx iris.Context) {
	var RequestParams MessageListRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	var msg services.CommonService[dao.SystemMsg]
	msg.Page = RequestParams.Page
	msg.PageSize = RequestParams.PageSize
	msg.WhereStr = append(msg.WhereStr, fmt.Sprintf("msg_classification = %v", RequestParams.MsgClassification))
	msg.Order = "created_at desc"
	if res, err := msg.SelectList(); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	} else {
		ctx.JSON(utils.Response{Code: iris.StatusOK, Message: iris.StatusText(iris.StatusOK), Data: iris.Map{"count": res.Total, "list": res.Data}})
		return
	}
}

/*
 *  DeleteMessageRequest
 *  @Description: 删除项目通知的请求参数，Id为需要删除的项目通知Id
 */

type DeleteMessageRequest struct {
	Id []uint `json:"id" validate:"required"`
}

// @Summary 删除项目通知
// @Description 删除项目通知
// @Tags 通知
// @Accept application/json
// @Produce application/json
// @param Accept-Version header string true "1.0.0"
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param param body DeleteMessageRequest true "删除项目通知参数"
// @Success 200 {object} utils.Response --> 成功后返回数据结构
// @Failure 400 {object} utils.ResponseError --> 失败后返回数据结构
// @Router /admin/message/del [post]
func DeleteMessageHandler(ctx iris.Context) {
	var RequestParams DeleteMessageRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	var claims services.CustomClaims
	if err := claims.ParseClaims(ctx); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	}
	/*if claims.Type == 2 {
		ctx.JSON(utils.ResponseError{Code: 403, Message: "权限不够"})
		return
	}*/
	var msgServe services.MessageService
	if err := msgServe.BatchRemoveMsgNew(RequestParams.Id); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	} else {
		ctx.JSON(utils.Response{Code: iris.StatusOK, Message: iris.StatusText(iris.StatusOK), Data: iris.StatusText(iris.StatusOK)})
		return
	}

}

type HomeNoticeEditRequest struct {
	//Id      uint   `json:"id"`
	Content string `json:"content"`
	Status  int    `json:"status"`
}

// @Summary 主页公告
// @Description 主页公告修改
// @Tags 通知
// @Accept application/json
// @Produce application/json
// @param Accept-Version header string true "1.0.0"
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param param body HomeNoticeEditRequest true "主页公告参数"
// @Success 200 {object} utils.Response --> 成功后返回数据结构
// @Failure 400 {object} utils.ResponseError --> 失败后返回数据结构
// @Router /admin/message/home_notice/edit [post]
func HomeNoticeEditHandler(ctx iris.Context) {
	var RequestParams HomeNoticeEditRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	var homeNotice dao.Common[dao.HomeNotice]
	if notice, err := homeNotice.First(map[string]interface{}{}); err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			var notice dao.HomeNotice
			notice.Status = RequestParams.Status
			notice.Content = RequestParams.Content
			if err := homeNotice.CreateOne(notice).Error; err != nil {
				ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
				return
			} else {
				ctx.JSON(utils.Response{Code: iris.StatusOK, Message: iris.StatusText(iris.StatusOK), Data: iris.StatusText(iris.StatusOK)})
				return
			}
		} else {
			ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
			return
		}
	} else {
		notice.Status = RequestParams.Status
		notice.Content = RequestParams.Content
		homeNotice.Query = map[string]interface{}{"id": notice.Id}
		if err := homeNotice.Save(notice).Error; err != nil {
			ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
			return
		} else {
			ctx.JSON(utils.Response{Code: iris.StatusOK, Message: iris.StatusText(iris.StatusOK), Data: iris.StatusText(iris.StatusOK)})
			return
		}

	}
}

// @Summary 获取主页公告详情
// @Description 获取主页公告详情
// @Tags 通知
// @Accept application/json
// @Produce application/json
// @param Accept-Version header string true "1.0.0"
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Success 200 {object} utils.Response --> 成功后返回数据结构
// @Failure 400 {object} utils.ResponseError --> 失败后返回数据结构
// @Router /admin/message/home_notice/detail [get]
func HomeNoticeDetailHandler(ctx iris.Context) {
	var homeNotice dao.Common[dao.HomeNotice]
	if notice, err := homeNotice.First(map[string]interface{}{}); err != nil {
		switch err {
		case gorm.ErrRecordNotFound:
			ctx.JSON(utils.Response{Code: iris.StatusOK, Message: iris.StatusText(iris.StatusOK), Data: ""})
			return
		default:
			ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
			return
		}
	} else {
		ctx.JSON(utils.Response{Code: iris.StatusOK, Message: iris.StatusText(iris.StatusOK), Data: notice})
		return
	}

}

type SendMessageGlobalRequest struct {
	MsgType    int    `json:"msg_type"`    //通知类型-全局通知才有此字段(1：所有团队，2：团队，3：个人)
	MsgWay     string `json:"msg_way"`     //通知形式。1：系统内通知，2：邮件通知，3：手机短信通知
	TeamNumber string `json:"team_number"` //团队编号（MsgType = 2时才有，不填则是全部团队）
	User       string `json:"user"`        //user_id 或者 email 或者 phone（MsgType = 3时才有）
	Content    string `json:"content"`     //通知内容
}

func SendMessageGlobalHandler(ctx iris.Context) {
	var RequestParams SendMessageGlobalRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	var param = make(map[string]string)
	param["team_number"] = RequestParams.TeamNumber
	param["user"] = RequestParams.User
	param["msg_way"] = RequestParams.MsgWay
	param["content"] = RequestParams.Content
	var messageServe services.MessageService
	if err := messageServe.SendMessageGlobal(RequestParams.MsgType, param); err != nil {
		ctx.JSON(utils.ResponseServerError(err))
		return
	} else {
		ctx.JSON(utils.ResponseOK())
		return
	}

}

type SendMessageProjecRequest struct {
	Permissions string `json:"permissions"` //项目权限
	Content     string `json:"content"`     //通知内容
}

func SendMessageProjectHandler(ctx iris.Context) {
	var RequestParams SendMessageProjecRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}

	var param = make(map[string]string)
	param["permissions"] = RequestParams.Permissions
	param["content"] = RequestParams.Content
	var messageServe services.MessageService

	if err := messageServe.SendMessageProject(param); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	} else {
		ctx.JSON(utils.Response{Code: iris.StatusOK, Message: iris.StatusText(iris.StatusOK), Data: iris.StatusText(iris.StatusOK)})
		return
	}

}

type QueryUserMsgListRequest struct {
	Page     int64 `json:"page"`
	PageSize int64 `json:"page_size"`
	//Status   int8   `json:"status"` //状态(0-未读,1-已读)
	UserId string `json:"user_id"`
}

func QueryUserMsgListHandler(ctx iris.Context) {
	var RequestParams QueryUserMsgListRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}

	type UserMsgInfo struct {
		dao.UserMsgInfo
		Content string `json:"content"`
		MsgType int    `json:"msg_type"`
	}
	var msg services.CommonService[UserMsgInfo]
	msg.Page = RequestParams.Page
	msg.PageSize = RequestParams.PageSize
	msg.LeftJoin = append(msg.LeftJoin, fmt.Sprintf("left join tas_system_msg m on m.id = tas_user_msg_info.msg_id "))
	msg.WhereStr = append(msg.WhereStr, fmt.Sprintf("tas_user_msg_info.system_user_id = '%v' and tas_user_msg_info.type = 0 ", RequestParams.UserId))
	msg.WhereStr = append(msg.WhereStr, fmt.Sprintf("m.msg_classification  = 1"))
	field := "tas_user_msg_info.*,m.content,m.msg_type"
	msg.SelectField = &field
	msg.Order = "tas_user_msg_info.id desc"
	if res, err := msg.SelectList(); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	} else {
		ctx.JSON(utils.Response{Code: iris.StatusOK, Message: iris.StatusText(iris.StatusOK), Data: iris.Map{"count": res.Total, "list": res.Data}})
		return
	}
}

type UpdateMsgStatusRequest struct {
	Id []uint `json:"id" validate:"required"`
}

func UpdateMsgStatusHandler(ctx iris.Context) {
	var RequestParams UpdateMsgStatusRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}

	type UserMsgInfo struct {
		dao.UserMsgInfo
		Content string `json:"content"`
	}
	var msg dao.Common[UserMsgInfo]
	msg.Query = map[string]interface{}{"id": RequestParams.Id}
	if err := msg.Update(map[string]interface{}{"status": MsgReadStatusYes}).Error; err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	} else {
		ctx.JSON(utils.ResponseOK())
		return
	}
}

type QueryIsUnReadMsgRequest struct {
	SystemUserId string `json:"system_user_id"`
}

func QueryIsUnReadMsgHandler(ctx iris.Context) {
	var RequestParams QueryIsUnReadMsgRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}

	var msg services.CommonService[dao.UserMsgInfo]
	msg.LeftJoin = append(msg.LeftJoin, fmt.Sprintf("LEFT JOIN tas_system_msg on tas_user_msg_info.msg_id = tas_system_msg.id"))
	msg.WhereStr = append(msg.WhereStr, fmt.Sprintf("system_user_id = '%v' ", RequestParams.SystemUserId))
	msg.WhereStr = append(msg.WhereStr, fmt.Sprintf("tas_user_msg_info.status = %v ", MsgReadStatusNo))
	msg.WhereStr = append(msg.WhereStr, fmt.Sprintf("tas_user_msg_info.type = %v ", TypeMsg))
	msg.WhereStr = append(msg.WhereStr, fmt.Sprintf("tas_system_msg.msg_classification = 1 "))
	if list, err := msg.FindWithLeftJoinAll(); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	} else {
		flag := false
		if len(list) > 0 {
			flag = true
		}
		ctx.JSON(utils.ResponseData(map[string]interface{}{"msg_read": flag}))
		return
	}
}

func QueryUserIncomeExchangeMsgHandler(ctx iris.Context) {
	var RequestParams QueryIsUnReadMsgRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}

	var balanceLogServe dao.Common[dao.SystemUserBalanceLog]
	if incomeCount, err := balanceLogServe.Count(map[string]interface{}{"read_status": MsgReadStatusNo, "log_type": BalanceLogLogTypeIn, "user_id": RequestParams.SystemUserId}); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	} else {
		incomesFlag := false
		if incomeCount > 0 {
			incomesFlag = true
		}
		var reviewRecordServe dao.Common[dao.SystemOrderReviewRecord]
		if reviewRecordCount, err := reviewRecordServe.Count(map[string]interface{}{"read_status": MsgReadStatusNo, "user_id": RequestParams.SystemUserId}); err != nil {
			ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
			return
		} else {
			reviewRecordFlag := false
			if reviewRecordCount > 0 {
				reviewRecordFlag = true
			}
			myIncomeFlag := false
			if incomesFlag || reviewRecordFlag {
				myIncomeFlag = true
			}
			ctx.JSON(utils.ResponseData(map[string]interface{}{"my_income": myIncomeFlag, "income_record": incomesFlag, "review_record": reviewRecordFlag}))
			return
		}
	}
}

type ReadUserIncomeExchangeMsgRequest struct {
	Ids  []uint `json:"ids" validate:"required"`
	Type string `json:"type" validate:"required"` //类型(1-我的收入,2兑换记录)
}

func ReadUserIncomeExchangeMsgHandler(ctx iris.Context) {
	var RequestParams ReadUserIncomeExchangeMsgRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	//我的收入已读
	if RequestParams.Type == "1" {
		var balanceLogServe dao.Common[dao.SystemUserBalanceLog]
		if err := balanceLogServe.BatchUpdate(RequestParams.Ids, map[string]interface{}{"read_status": MsgReadStatusYes}).Error; err != nil {
			ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
			return
		} else {
			ctx.JSON(utils.ResponseOK())
			return
		}
	} else if RequestParams.Type == "2" {
		var reviewRecordServe dao.Common[dao.SystemOrderReviewRecord]
		if err := reviewRecordServe.BatchUpdate(RequestParams.Ids, map[string]interface{}{"read_status": MsgReadStatusYes}).Error; err != nil {
			ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
			return
		} else {
			ctx.JSON(utils.ResponseOK())
			return
		}
	}
}

type MessageDetailRequest struct {
	Id string `json:"id" validate:"required"`
}

func MessageDetailHandler(ctx iris.Context) {
	var RequestParams MessageDetailRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}
	var msg dao.Common[dao.SystemMsg]
	if res, err := msg.First(map[string]interface{}{"id": RequestParams.Id}); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	} else {
		var msgWay dao.Common[dao.SystemMsgWay]
		if way, err := msgWay.FindAll(map[string]interface{}{"message_id": res.Id}); err != nil {
			ctx.JSON(utils.Response{Code: iris.StatusOK, Message: iris.StatusText(iris.StatusOK), Data: iris.Map{"msg": res}})
			return
		} else {
			ctx.JSON(utils.Response{Code: iris.StatusOK, Message: iris.StatusText(iris.StatusOK), Data: iris.Map{"msg": res, "way": way}})
			return
		}
	}
}

type MessageEditRequest struct {
	Id      string `json:"id" validate:"required"`
	Content string `json:"content"`
}

func MessageEditHandler(ctx iris.Context) {
	var RequestParams MessageEditRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}

	var msg dao.Common[dao.SystemMsg]
	if res, err := msg.First(map[string]interface{}{"id": RequestParams.Id}); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	} else {
		updateMap := map[string]interface{}{"content": RequestParams.Content}
		if err := msg.UpdateOne(res.Id, updateMap); err != nil {
			ctx.JSON(utils.ResponseOK())
			return
		}
	}
}

type MessageDelRequest struct {
	Id string `json:"id" validate:"required"`
}

func MessageDelHandler(ctx iris.Context) {
	var RequestParams MessageDelRequest
	if err := ctx.ReadJSON(&RequestParams); err != nil {
		handler.ArgumentErrorHandle(err, ctx)
		return
	}

	var msg dao.Common[dao.SystemMsg]
	var msgWay dao.Common[dao.SystemMsgWay]
	var userMsg dao.Common[dao.UserMsgInfo]
	if res, err := msg.First(map[string]interface{}{"id": RequestParams.Id}); err != nil {
		ctx.JSON(utils.ResponseError{Code: iris.StatusInternalServerError, Message: err.Error()})
		return
	} else {
		if err := msg.DeleteById(res.Id).Error; err != nil {
			ctx.JSON(utils.ResponseServerError(err))
			return
		} else {
			if err := msgWay.DeleteByStringColumn("message_id", utils.UintToString(res.Id)).Error; err != nil {
				ctx.JSON(utils.ResponseServerError(err))
				return
			} else {
				if err := userMsg.DeleteByStringColumn("msg_id", utils.UintToString(res.Id)).Error; err != nil {
					ctx.JSON(utils.ResponseServerError(err))
					return
				} else {
					ctx.JSON(utils.ResponseOK())
					return
				}
			}
		}
	}
}
